package com.example.icar.rosmaster;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.SocketException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Rosmaster客户端，用于与Rosmaster小车进行网络通信
 */
public class RosmasterClient {
    private static final String TAG = "RosmasterClient";
    
    private Socket socket;
    private PrintWriter writer;
    private BufferedReader reader;
    private ExecutorService executorService;
    private boolean isRunning = false;
    private String ipAddress;
    private int port;
    
    /**
     * 构造函数
     * @param ipAddress IP地址
     * @param port 端口
     */
    public RosmasterClient(String ipAddress, int port) {
        this.ipAddress = ipAddress;
        this.port = port;
        this.executorService = Executors.newCachedThreadPool();
        Log.d(TAG, "创建RosmasterClient，目标地址: " + ipAddress + ":" + port);
    }

    /**
     * 构造函数
     * @param socket 已连接的Socket
     * @throws IOException 如果初始化IO流失败
     */
    public RosmasterClient(Socket socket) throws IOException {
        this.socket = socket;
        this.ipAddress = socket.getInetAddress().getHostAddress();
        this.port = socket.getPort();
        Log.d(TAG, "创建RosmasterClient，连接到: " + ipAddress + ":" + port);
        
        try {
            this.writer = new PrintWriter(socket.getOutputStream(), true);
            this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            this.executorService = Executors.newCachedThreadPool();
            Log.d(TAG, "RosmasterClient初始化成功");
        } catch (IOException e) {
            Log.e(TAG, "初始化IO流失败: " + e.toString());
            throw e;
        }
    }
    
    /**
     * 连接到服务器
     * @return 连接是否成功
     */
    public boolean connect() {
        try {
            Log.d(TAG, "尝试连接到服务器: " + ipAddress + ":" + port);
            socket = new Socket(ipAddress, port);
            writer = new PrintWriter(socket.getOutputStream(), true);
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            Log.d(TAG, "连接成功");
            return true;
        } catch (IOException e) {
            Log.e(TAG, "连接失败: " + e.toString());
            return false;
        }
    }
    
    /**
     * 获取连接的IP地址
     * @return IP地址
     */
    public String getIpAddress() {
        return ipAddress;
    }
    
    /**
     * 检查连接是否有效
     * @return 连接状态
     */
    public boolean isConnected() {
        return socket != null && socket.isConnected() && !socket.isClosed();
    }
    
    /**
     * 开始接收数据
     */
    public void startReceiving() {
        isRunning = true;
        Log.d(TAG, "开始接收数据线程");
        
        executorService.execute(() -> {
            try {
                String line;
                Log.d(TAG, "等待接收数据...");
                while (isRunning && (line = reader.readLine()) != null) {
                    processResponse(line);
                }
                Log.d(TAG, "接收数据线程结束");
            } catch (SocketException e) {
                Log.e(TAG, "Socket异常: " + e.toString());
                isRunning = false;
            } catch (IOException e) {
                Log.e(TAG, "接收数据时出错: " + e.toString());
                isRunning = false;
            }
        });
    }
    
    /**
     * 发送命令到Rosmaster
     * @param command 要发送的命令
     */
    public void sendCommand(String command) {
        if (writer != null && isConnected()) {
            writer.println(command);
            writer.flush(); // 确保数据被发送
            Log.d(TAG, "发送TCP命令: " + command);
        } else {
            Log.e(TAG, "发送命令失败: 连接已关闭或无效");
        }
    }
    
    /**
     * 发送原始TCP命令到Rosmaster
     * @param command 要发送的命令
     */
    public void sendTcpCommand(String command) {
        if (writer != null && isConnected()) {
            writer.println(command);
            writer.flush(); // 确保数据被发送
            Log.d(TAG, "发送TCP命令: " + command);
        } else {
            Log.e(TAG, "发送命令失败: 连接已关闭或无效");
        }
    }
    
    /**
     * 处理从Rosmaster接收到的响应
     * @param response 响应数据
     */
    private void processResponse(String response) {
        Log.d(TAG, "收到响应: " + response);
        // 根据响应格式解析并处理数据
        // 这里可以添加回调接口通知UI更新
    }
    
    /**
     * 关闭连接
     * @throws IOException 如果关闭连接时出错
     */
    public void close() throws IOException {
        Log.d(TAG, "关闭RosmasterClient连接");
        isRunning = false;
        
        try {
            if (writer != null) {
                writer.close();
            }
            
            if (reader != null) {
                reader.close();
            }
            
            if (socket != null && !socket.isClosed()) {
                socket.close();
                Log.d(TAG, "Socket已关闭");
            }
            
            if (executorService != null) {
                executorService.shutdown();
            }
        } catch (IOException e) {
            Log.e(TAG, "关闭连接时出错: " + e.toString());
            throw e;
        }
    }
} 